#! /bin/bash


ETCDCTL_PATH='{{ bin_dir }}/etcdctl'
ENDPOINTS='{{ etcd_endpoint }}'
ETCD_DATA_DIR="{{ etcd_data_dir }}"
BACKUP_DIR="{{ etcd_backup_prefix }}/etcd-$(date +%Y-%m-%d_%H:%M:%S)"

ETCDCTL_CERT="{{ etcd_cert_dir }}/admin-{{ inventory_hostname }}.pem"
ETCDCTL_KEY="{{ etcd_cert_dir }}/admin-{{ inventory_hostname }}-key.pem"
ETCDCTL_CA_FILE="{{ etcd_cert_dir }}/ca.pem"


[ ! -d $BACKUP_DIR ] && mkdir -p $BACKUP_DIR


export ETCDCTL_API=2;$ETCDCTL_PATH backup --data-dir $ETCD_DATA_DIR --backup-dir $BACKUP_DIR

sleep 3

{
export ETCDCTL_API=3;$ETCDCTL_PATH --endpoints="$ENDPOINTS" snapshot save $BACKUP_DIR/snapshot.db \
                                   --cacert="$ETCDCTL_CA_FILE" \
                                   --cert="$ETCDCTL_CERT" \
                                   --key="$ETCDCTL_KEY"
} > /dev/null 

sleep 3

cd $BACKUP_DIR/../;ls -lt |awk '{if(NR>({{ keep_backup_number }}+1)){print "rm -rf "$9}}'|sh